package net.tatu.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import net.tatu.model.UploadFile;
import net.tatu.model.User;
import net.tatu.service.UploadService;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class UploadServiceImpl implements UploadService {
	Logger log = Logger.getLogger(UploadServiceImpl.class);

	@Override
	public String uploadForm(UploadFile file, String imgType, HttpServletRequest request) throws Exception {
		file.validateFile();
		//imagType=(1:身份证正面；0:身份证反面)
		String path = getPath(imgType);
		String fileName = getFileName(file, request);
		uploadFile(path, file.getImgFile(), fileName);
		return path + "/" + fileName;
	}
	
	private String getFileName(UploadFile file, HttpServletRequest request) {
		String fileName = "";
		String type = file.getImgFile().getOriginalFilename();
		type = (String) type.subSequence(type.indexOf("."), type.length());
		try{
			User user = (User) request.getSession().getAttribute("user");
			fileName = String.valueOf(user.getUserId()) + type;
		}catch(Exception e){
			e.printStackTrace();
			log.error("用户没登陆及开始执行上传操作！");
		}
		log.debug("最后得到的文件名称：" + fileName);
		return fileName;
	}

	private String getPath(String imgType) {
		String dir = System.getProperty("user.dir");
		dir = (String) dir.subSequence(0, dir.length()-3);
		
		dir = "/work/";
		
		
		
		
		dir = dir + "webapps/bimFront/userImages";
		if(imgType.equals("1")){
			dir = dir + "/certFrontPhoto";
		}else if (imgType.equals("0")){
			dir = dir + "/certObversePhoto";
		}else if (imgType.equals("2")){
			dir = dir + "/businessCertPhoto";
		}else if (imgType.equals("3")){
			dir = dir + "/taxRegCertPhoto";
		}else if (imgType.equals("4")){
			dir = dir + "/tenderFile";
		}else if (imgType.equals("5")){
			dir = dir + "/tenderPic";
		}else{
			log.error("imgType:不合法！imgType:" + imgType);
		}
		log.debug("最后得到的存储路径：" + dir);
		return dir;
	}

	private boolean uploadFile(String destinationDir, MultipartFile file, String filename)
			throws Exception {
		 log.info("文件长度: " + file.getSize()); 
         log.info("文件类型: " + file.getContentType()); 
         log.info("文件名称: " + file.getName()); 
         log.info("文件原名: " + file.getOriginalFilename()); 
         log.info("========================================"); 
         try {  
        	 File fileTest =new File(destinationDir);    
        	 //如果文件夹不存在则创建    
        	 if  (!fileTest .exists()  && !fileTest .isDirectory()){       
        		log.info("//不存在");  
				boolean b = fileTest.mkdirs(); 
				log.info("创建目录：" + b);
        	 }else{  
         		log.info("//目录存在");  
         	 } 
             SaveFileFromInputStream(file.getInputStream(), destinationDir, filename);   
         } catch (IOException e) {   
             log.info(e.getMessage());   
             return false;   
         }   
		return true;
	} 
	private void SaveFileFromInputStream(InputStream stream,String path,String filename) throws IOException {         
	   FileOutputStream outputStream = new FileOutputStream( path + "/"+ filename);   
	   int byteCount = 0;
	   byte[] bytes = new byte[1024];
	   while ((byteCount = stream.read(bytes)) != -1){
	        outputStream.write(bytes, 0, byteCount);
	   }
	   outputStream.close();   
	   stream.close();  
	} 

}
